package com.zgq.share.db;

import com.zgq.share.entity.ShareBean;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ShareInfoDao {
	
	private Context context;
	private DBOpenHelper dbHelper;
	
	public ShareInfoDao(Context context) {
		this.context = context;
	}
	
	public void open() {
		if (dbHelper == null) {
			dbHelper = new DBOpenHelper(context);
		}
	}
	
	public void close() {
		if (dbHelper != null) {
			dbHelper.close();
		}
	}
	
	public long addShareInfo(ShareBean share) {
		
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(ShareInfoColumn.NAME, share.getName());
		values.put(ShareInfoColumn.TOKEN, share.getToken());
		values.put(ShareInfoColumn.SECRET, share.getSecret());
		values.put(ShareInfoColumn.SELECTED, share.isSelected() ? 1 : 0);

		return db.insertOrThrow(DBOpenHelper.T_WEIBO_AUTH, null, values);
	}
	
	/**
	 * 更新
	 * 
	 * @param
	 * @return
	 */
	public ShareBean getShareSetting(String name) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ShareBean share = null;

		Cursor cursor = db.query(DBOpenHelper.T_WEIBO_AUTH,
				ShareInfoColumn.PROJECTION, " name = ?", new String[] { name }, null, null, null);

		if (cursor.getCount() > 0) {
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
					.moveToNext()) {
				share = new ShareBean();

				share.setId(cursor.getInt(0));
				share.setName(cursor.getString(1));
				share.setToken(cursor.getString(2));
				share.setSecret(cursor.getString(3));
				share.setSelected(cursor.getInt(4) == 0 ? false : true);
			}
		}
		cursor.close();
		cursor = null;

		return share;
	}
	
	public boolean delete(String name) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		int ret = db.delete(DBOpenHelper.T_WEIBO_AUTH, " name = ? ",
				new String[] { name });
		return ret > 0 ? true : false;
	}

}
